import { ref, onUnmounted, reactive } from 'vue'
import { message } from 'ant-design-vue'
import type { AiProcessMessage, WebSocketConnectionInfo, AiProcessStatus } from '@/types/websocket'
import { apiClient } from '@/api/config'

export function useWebSocket() {
  const ws = ref<WebSocket | null>(null)
  const isConnected = ref(false)
  const isConnecting = ref(false)
  const messages = ref<AiProcessMessage[]>([])
  const aiProcessStatuses = reactive<Map<number, AiProcessStatus>>(new Map())

  let heartbeatTimer: number | null = null
  let reconnectTimer: number | null = null
  let reconnectAttempts = 0
  const maxReconnectAttempts = 5

  // 获取WebSocket连接信息
  const getConnectionInfo = async (): Promise<WebSocketConnectionInfo> => {
    try {
      const response = await apiClient.get('/websocket/connection-info')
      console.log('WebSocket连接信息响应:', response.data)

      // 检查响应结构
      if (response.data && typeof response.data === 'object') {
        // 如果有 code 字段，检查是否成功
        if ('code' in response.data && response.data.code !== 200) {
          throw new Error(response.data.message || 'Failed to get connection info')
        }

        // 如果有 data 字段，返回 data；否则直接返回 response.data
        if ('data' in response.data && response.data.data) {
          return response.data.data
        } else if ('wsUrl' in response.data) {
          // 直接返回连接信息
          return response.data as WebSocketConnectionInfo
        }
      }

      throw new Error('Invalid response structure')
    } catch (error: unknown) {
      console.error('获取WebSocket连接信息失败:', error)
      throw error
    }
  }

  // 连接WebSocket
  const connect = async () => {
    if (isConnected.value || isConnecting.value) {
      return
    }

    try {
      isConnecting.value = true
      console.log('正在建立WebSocket连接...')

      // 获取连接信息
      const connectionInfo = await getConnectionInfo()

      // 构建WebSocket URL
      let wsUrl = connectionInfo.fullWsUrl

      // 在开发环境下，使用前端开发服务器的地址，但保持后端的WebSocket路径
      if (import.meta.env.DEV) {
        // 开发环境：使用前端服务器地址 + 后端WebSocket路径
        const wsPath = wsUrl.replace(/^ws:\/\/[^\/]+/, '') // 提取路径部分
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
        wsUrl = `${protocol}//${window.location.host}${wsPath}`
      } else {
        // 生产环境：替换为当前域名
        if (wsUrl.includes('localhost:8088')) {
          wsUrl = wsUrl.replace('localhost:8088', window.location.host)
        }
        // 如果是https，则使用wss
        if (window.location.protocol === 'https:') {
          wsUrl = wsUrl.replace('ws://', 'wss://')
        }
      }

      // 建立WebSocket连接
      console.log('尝试连接WebSocket:', wsUrl)
      ws.value = new WebSocket(wsUrl)

      ws.value.onopen = () => {
        console.log('WebSocket连接已建立')
        isConnected.value = true
        isConnecting.value = false
        reconnectAttempts = 0
        startHeartbeat()
        message.success('AI处理通知连接已建立')
      }

      ws.value.onmessage = (event) => {
        try {
          const messageData: AiProcessMessage = JSON.parse(event.data)
          handleMessage(messageData)
        } catch (error: unknown) {
          console.error('解析WebSocket消息失败:', error)
        }
      }

      ws.value.onclose = (event) => {
        console.log('WebSocket连接已关闭:', event.code, event.reason)
        isConnected.value = false
        isConnecting.value = false
        stopHeartbeat()

        // 非正常关闭时尝试重连
        if (event.code !== 1000 && reconnectAttempts < maxReconnectAttempts) {
          const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000)
          console.log(`${delay / 1000}秒后尝试重连...`)
          reconnectTimer = window.setTimeout(() => {
            reconnectAttempts++
            connect()
          }, delay)
        } else if (reconnectAttempts >= maxReconnectAttempts) {
          console.error('WebSocket重连次数已达上限')
          message.error('AI处理通知连接失败，请刷新页面重试')
        }
      }

      ws.value.onerror = (error) => {
        console.error('WebSocket错误:', error)
        isConnected.value = false
        isConnecting.value = false
      }
    } catch (error: unknown) {
      console.error('建立WebSocket连接失败:', error)
      isConnecting.value = false
      // 不在这里显示错误消息，让调用方决定是否显示
      throw error
    }
  }

  // 处理WebSocket消息
  const handleMessage = (messageData: AiProcessMessage) => {
    messages.value.push(messageData)

    // 保持消息列表不超过100条
    if (messages.value.length > 100) {
      messages.value = messages.value.slice(-100)
    }

    switch (messageData.type) {
      case 'CONNECTION_SUCCESS':
        console.log('WebSocket连接成功确认')
        break

      case 'AI_PROCESS_START':
        if (messageData.pictureId) {
          updateAiProcessStatus(messageData.pictureId, {
            pictureId: messageData.pictureId,
            status: 'processing',
            message: messageData.message,
            timestamp: messageData.timestamp,
          })
          console.log(`开始处理图片 ${messageData.pictureId}`)
        }
        break

      case 'AI_PROCESS_SUCCESS':
        if (messageData.pictureId) {
          updateAiProcessStatus(messageData.pictureId, {
            pictureId: messageData.pictureId,
            status: 'success',
            message: messageData.message,
            result: {
              title: messageData.aiTitle || '',
              category: messageData.aiCategory || '',
              tags: messageData.aiTags || [],
            },
            timestamp: messageData.timestamp,
          })
          console.log(`图片 ${messageData.pictureId} 处理成功:`, {
            title: messageData.aiTitle,
            category: messageData.aiCategory,
            tags: messageData.aiTags,
          })
          message.success(`图片"${messageData.aiTitle}"AI处理完成`)
        }
        break

      case 'AI_PROCESS_ERROR':
        if (messageData.pictureId) {
          updateAiProcessStatus(messageData.pictureId, {
            pictureId: messageData.pictureId,
            status: 'error',
            message: messageData.message,
            error: messageData.error,
            timestamp: messageData.timestamp,
          })
          console.error(`图片 ${messageData.pictureId} 处理失败:`, messageData.error)
          message.error(`图片AI处理失败: ${messageData.error}`)
        }
        break

      case 'HEARTBEAT':
        // 心跳响应，不需要特殊处理
        break

      default:
        console.log('收到未知类型的WebSocket消息:', messageData)
    }
  }

  // 更新AI处理状态
  const updateAiProcessStatus = (pictureId: string, status: AiProcessStatus) => {
    aiProcessStatuses.set(pictureId as unknown as number, status)
  }

  // 获取AI处理状态
  const getAiProcessStatus = (pictureId: string): AiProcessStatus | undefined => {
    return aiProcessStatuses.get(pictureId as unknown as number)
  }

  // 清除AI处理状态
  const clearAiProcessStatus = (pictureId: string) => {
    aiProcessStatuses.delete(pictureId as unknown as number)
  }

  // 清除所有AI处理状态
  const clearAllAiProcessStatuses = () => {
    aiProcessStatuses.clear()
  }

  // 心跳机制
  const startHeartbeat = () => {
    heartbeatTimer = window.setInterval(() => {
      if (ws.value?.readyState === WebSocket.OPEN) {
        ws.value.send('ping')
      }
    }, 30000) // 30秒发送一次心跳
  }

  const stopHeartbeat = () => {
    if (heartbeatTimer) {
      clearInterval(heartbeatTimer)
      heartbeatTimer = null
    }
  }

  // 断开连接
  const disconnect = () => {
    if (reconnectTimer) {
      clearTimeout(reconnectTimer)
      reconnectTimer = null
    }
    if (ws.value) {
      ws.value.close(1000, '用户主动断开')
      ws.value = null
    }
    isConnected.value = false
    isConnecting.value = false
    stopHeartbeat()
    reconnectAttempts = 0
  }

  // 获取最近的消息
  const getRecentMessages = (count = 10) => {
    return messages.value.slice(-count).reverse()
  }

  // 获取所有处理中的AI任务
  const getProcessingTasks = () => {
    const processing: AiProcessStatus[] = []
    aiProcessStatuses.forEach((status) => {
      if (status.status === 'processing') {
        processing.push(status)
      }
    })
    return processing
  }

  // 获取已完成的AI任务
  const getCompletedTasks = () => {
    const completed: AiProcessStatus[] = []
    aiProcessStatuses.forEach((status) => {
      if (status.status === 'success' || status.status === 'error') {
        completed.push(status)
      }
    })
    return completed
  }

  // 组件卸载时断开连接
  onUnmounted(() => {
    disconnect()
  })

  return {
    // 状态
    isConnected,
    isConnecting,
    messages,
    aiProcessStatuses,

    // 方法
    connect,
    disconnect,
    getAiProcessStatus,
    clearAiProcessStatus,
    clearAllAiProcessStatuses,
    getRecentMessages,
    getProcessingTasks,
    getCompletedTasks,
  }
}
